package guoanmaker.provider.business.service;

import static org.mockito.Matchers.intThat;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.transaction.Transactional;

import org.aspectj.weaver.ast.Literal;
import org.springframework.stereotype.Service;

import guoanmaker.provider.business.dao.PersonalAppraiseDao;
import guoanmaker.provider.business.dao.ProvideOrderFormDao;
import guoanmaker.provider.business.model.OperatorCoupons;
import guoanmaker.provider.business.model.OperatorQuestionOrder;
import guoanmaker.provider.business.model.OperatorSecckill;
import guoanmaker.provider.business.model.PersonalInvoice;
import guoanmaker.provider.business.model.PersonalUserCoupon;
import guoanmaker.provider.business.model.ProvideCommodity;
import guoanmaker.provider.business.model.ProvideOrderForm;
import guoanmaker.provider.business.model.ReturnResult;
import guoanmaker.provider.business.modelnobind.JsonAnalyze;
import guoanmaker.provider.business.modelnobind.ProvideOrderFormForOrder;
import guoanmaker.provider.business.modelnobind.UnreadOrderNum;
import guoanmaker.provider.business.repository.OperatorCouponsRepository;
import guoanmaker.provider.business.repository.OperatorQuestionOrderRepository;
import guoanmaker.provider.business.repository.OperatorSecckillRepository;
import guoanmaker.provider.business.repository.PersonalInvoiceRepository;
import guoanmaker.provider.business.repository.PersonalUserCouponRepository;
import guoanmaker.provider.business.repository.ProvideCommodityRepository;
import guoanmaker.provider.business.repository.ProvideOrderFormRepository;
import guoanmaker.provider.helper.common.abstractobj.ApiController;
import guoanmaker.provider.helper.common.util.SystemHelper;
/**
 * 
* @ClassName: ProvideOrderFormService 
* @Description: 订单service
* @author Yvonne_MGL
* @date 2017年7月6日 下午3:30:30 
*  
 */
@Service
public class ProvideOrderFormService {
	@Resource
	private ProvideOrderFormDao provideOrderFormDao;
	
	@Resource
	private ProvideOrderFormRepository provideOrderFormRepository;
	
	@Resource
	private  ProvideCommodityRepository provideCommodityRepository;
	
	@Resource
	private PersonalInvoiceRepository personalInvoiceRepository;
	
	@Resource
	private PersonalUserCouponRepository personalUserCouponRepository;
	
	@Resource
	private PersonalAppraiseDao personalAppraiseDao;
	
	@Resource
	private OperatorCouponsRepository operatorCouponsRepository;
	
	@Resource
	private OperatorQuestionOrderRepository operatorQuestionOrderRepository;
	
	@Resource
	private OperatorSecckillRepository operatorSecckillRepository;
	/**
	 * 
	* @Description: 根据条件查询服务商订单(简单查询,多表关联尽量不要用)
	* @param orderStatus 订单状态1待支付  2待接单  3服务中  4待确认   5退款处理中   6已完成   7已关闭
	* @param placeOrderTimeBegin 最早下单时间
	* @param placeOrderTimeEnd 最晚下单时间
	* @param priceBegin  最低价
	* @param priceEnd   最高价
	* @param commodityNameOrUserPhone  商品名称或者用户手机号
	* @param pageNumber  分页页数 ,从0开始
	* @param pageSize  分页每业条数
	* @param @throws Exception
	* @author Yvonne_MGL 
	* @date 2017年7月6日 下午3:31:02     
	* @return Page<ProvideOrderFormForOrder>    
	* @throws 
	 */
	public Map findByProperties(String orderStatus, String placeOrderTimeBegin, String placeOrderTimeEnd,
			Double priceBegin, Double priceEnd, String commodityNameOrUserPhone, String businessid, Integer pageNumber, Integer pageSize) throws Exception{
		return provideOrderFormDao.findByProperties(orderStatus, placeOrderTimeBegin, placeOrderTimeEnd, priceBegin, priceEnd, commodityNameOrUserPhone, businessid, pageNumber, pageSize);
		
	}
	
	/**
	 * 
	* @Description: 根据订单id获取订单详情
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月12日 上午11:37:12     
	* @return ProvideOrderFormForOrder    
	* @throws 
	 */
	public ProvideOrderFormForOrder findById(String id){
		return provideOrderFormDao.findByid(id);
	}
	
	/**
	 * 
	* @Description: 修改议价商品订单价格 
	* @param id 订单id
	* @param price 修改之后的价格
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 上午9:49:41     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult modifyPrice(String id,Double price){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("14")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许修改价格");
			}else{
				if(price<0){
					returnResult.setKey("error");
					returnResult.setValue("修改价格不能小于0");
				}else{
					orderForm.setRealPrice(price);
					orderForm.setTruePrice(price);
					orderForm.setOrderStatus("1");
					orderForm.setIsOverChangePrice("1");
					orderForm.setIsRead("1");
					provideOrderFormRepository.save(orderForm);
					returnResult.setKey("success");
		    		returnResult.setValue("修改价格成功");
				}
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 接单 
	* @param id  订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 上午10:20:38     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult acceptOrder(String id){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("2")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				orderForm.setOrderStatus("3");
				orderForm.setAcceptOrderTime(new Date());
				orderForm.setIsRead("1");
				provideOrderFormRepository.save(orderForm);
				returnResult.setKey("success");
	    		returnResult.setValue("接单成功");
			}
		}
		
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 关闭待支付订单,拒绝已支付订单 
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 上午10:49:03     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult closeOrder(String id,String closeType,String beRefunds)throws Exception{
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		String beSave="0";
		PersonalUserCoupon puCoupon=null;
		OperatorCoupons oCoupons=null;
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(closeType==null||(!closeType.equals("1")&&!closeType.equals("2")&&!closeType.equals("3")&&!closeType.equals("4")&&!closeType.equals("5"))){
				returnResult.setKey("error");
				returnResult.setValue("关闭方式不正确");
			}else{
				ProvideCommodity provideCommodity=orderForm.getCommodity();
				if((closeType.equals("2")&&orderForm.getOrderStatus().equals("2"))||(closeType.equals("3")&&orderForm.getOrderStatus().equals("2"))
						||(closeType.equals("5")&&orderForm.getOrderStatus().equals("2"))
						||(closeType.equals("4")&&beRefunds!=null&&beRefunds.equals("1")&&(orderForm.getOrderStatus().equals("2")||orderForm.getOrderStatus().equals("3")||orderForm.getOrderStatus().equals("4")))){
					
					int price=Integer.parseInt(new DecimalFormat("#").format(orderForm.getRealPrice()*100));
					if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
						price=price-Integer.parseInt((orderForm.getPreferentialMoney() * 100 + "").substring(0, (orderForm.getPreferentialMoney() * 100 + "").indexOf(".")));
						if(orderForm.getSpikeid()==null||orderForm.getSpikeid().equals("")){
							puCoupon=personalUserCouponRepository.findOne(orderForm.getCouponid());
							puCoupon.setIsUsed("0");
							oCoupons=puCoupon.getOperatorCoupon();
							oCoupons.setBeenused(oCoupons.getBeenused()-1);
						}
					}
					
					String url=ApiController.PAY_URL+"askRefund.php";
					String param="isJava=1&id="+orderForm.getDefrayNumber()+"&ask_name="+orderForm.getUser().getUsername()
							+"&ask_amount="+price+"&ask_description="+URLEncoder.encode("订单关闭发起退款", "UTF-8");
					String json=SystemHelper.httpGetHelper(url, param);
					
					if(json.indexOf("SUCCESS")<=0){
						returnResult.setKey("error");
			    		returnResult.setValue("提交退款失败，请重新处理");
					}else{
						Double preferentialMoney=0.00;
						if(puCoupon!=null){
							preferentialMoney=orderForm.getPreferentialMoney();
						}
						orderForm.setRefundsAmount(orderForm.getRealPrice()-preferentialMoney);
						orderForm.setCommission(new BigDecimal(0.00));
						orderForm.setBail(new BigDecimal(0.00));
						orderForm.setOrderStatus("11");
						orderForm.setCloseType(closeType);
						orderForm.setCloseTime(new Date());
						orderForm.setPreferentialMoney(0.00);
						//orderForm.setCouponid("");
						if(preferentialMoney!=0.00){
							orderForm.setReturnPreferentialMoney(preferentialMoney);
						}
						orderForm.setCouponName("");
						orderForm.setFullOrPartRefunds("2");
						orderForm.setRealPrice(0.00);
						beSave="1";
					}	
					
				}else if((closeType.equals("1")&&(orderForm.getOrderStatus().equals("1")||orderForm.getOrderStatus().equals("14")))
						||(closeType.equals("3")&&(orderForm.getOrderStatus().equals("1")||orderForm.getOrderStatus().equals("14")))
						||(closeType.equals("4")&&(orderForm.getOrderStatus().equals("1")||orderForm.getOrderStatus().equals("14")))
						||(closeType.equals("5")&&(orderForm.getOrderStatus().equals("1")||orderForm.getOrderStatus().equals("14")))){
					orderForm.setOrderStatus("7");
					orderForm.setCloseType(closeType);
					orderForm.setCloseTime(new Date());
					beSave="1";
				}else if(closeType.equals("4")&&(beRefunds==null||!beRefunds.equals("1"))&&(orderForm.getOrderStatus().equals("2")||orderForm.getOrderStatus().equals("3")||orderForm.getOrderStatus().equals("4"))){
					orderForm.setOrderStatus("15");
					orderForm.setCloseType(closeType);
					orderForm.setCloseTime(new Date());
					beSave="1";
				}
				if(beSave.equals("1")){
					if(provideCommodity.getStock()==null){
						if(orderForm.getOrderType().equals("3")){
							provideCommodity.setStock(orderForm.getQuantity());
						}else{
							provideCommodity.setStock(1);
						}
						
					}else{
						if(orderForm.getOrderType().equals("3")){
							provideCommodity.setStock(provideCommodity.getStock()+orderForm.getQuantity());
						}else{
							provideCommodity.setStock(provideCommodity.getStock()+1);
						}
					}
					if(provideCommodity.getCommodityState()==null||provideCommodity.getCommodityState()==0||provideCommodity.getSalesVolume()<=0){
						provideCommodity.setSalesVolume(0);
					}else{
						if(orderForm.getOrderType().equals("3")){
							provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()-orderForm.getQuantity());
						}else{
							provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()-1);
						}
						
					}
					if(provideCommodity.getType().equals("3")&&provideCommodity.getCommodityState()==7&&provideCommodity.getRegistrationEndTime().after(new Date())){
						provideCommodity.setCommodityState(2);
					}
					provideCommodityRepository.save(provideCommodity);
					orderForm.setCloseTime(new Date());
					orderForm.setCloseType(closeType);
					orderForm.setIsRead("1");
					provideOrderFormRepository.save(orderForm);
					if(puCoupon!=null){
						personalUserCouponRepository.save(puCoupon);
						operatorCouponsRepository.save(oCoupons);
					}
					if(orderForm.getSpikeid()!=null){
						OperatorSecckill secckill=operatorSecckillRepository.findOne(orderForm.getSpikeid());
						if(orderForm.getOrderType().equals("3")){
							secckill.setSkNum(secckill.getSkNum()+orderForm.getQuantity());
						}else{
							secckill.setSkNum(secckill.getSkNum()+1);
						}
						secckill.setSkSellNum(secckill.getSkSellNum()-1);
						operatorSecckillRepository.save(secckill);
					}
					
					
					returnResult.setKey("success");
		    		returnResult.setValue("订单已关闭");
				}else{
					returnResult.setKey("error");
					returnResult.setValue("操作不正确");
				}
			}
		}
		return returnResult;
	}
	
	
	/**
	 * 
	* @Description: 关闭待支付订单,拒绝已支付订单 
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年9月7日 下午8:49:03     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult closeOrderForOperator(String id,Double amount)throws Exception{
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		String beSave="0";
		PersonalUserCoupon puCoupon=null;
		OperatorCoupons oCoupons=null;
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			ProvideCommodity provideCommodity=orderForm.getCommodity();
			if(orderForm.getOrderStatus().equals("1")||orderForm.getOrderStatus().equals("14")){
				orderForm.setOrderStatus("7");
				beSave="1";
			}else if(orderForm.getOrderStatus().equals("2")||orderForm.getOrderStatus().equals("3")||orderForm.getOrderStatus().equals("4")||orderForm.getOrderStatus().equals("9")){
				if(amount==null||amount==0){
					orderForm.setOrderStatus("15");
					orderForm.setFullOrPartRefunds("");
					orderForm.setRefundsAmount(0.0);
					beSave="1";
				}else{
					Double preferentialMoney=0.00;
					if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
						preferentialMoney=orderForm.getPreferentialMoney();
					}
					if(amount<0||amount>orderForm.getRealPrice()-preferentialMoney){
						returnResult.setKey("error");
						returnResult.setValue("退款金额不正确");
					}else{
						if(amount==orderForm.getRealPrice()-preferentialMoney){
							orderForm.setFullOrPartRefunds("2");
							if(orderForm.getCouponid()!=null&&!orderForm.getCouponid().equals("")){
								puCoupon=personalUserCouponRepository.findOne(orderForm.getCouponid());
								puCoupon.setIsUsed("0");
								oCoupons=puCoupon.getOperatorCoupon();
								oCoupons.setBeenused(oCoupons.getBeenused()-1);
								//orderForm.setCouponid("");
								if(preferentialMoney!=0.00){
									orderForm.setReturnPreferentialMoney(preferentialMoney);
								}
								orderForm.setCouponName("");
							}
							if(provideCommodity.getStock()==null){
								provideCommodity.setStock(1);
							}else{
								provideCommodity.setStock(provideCommodity.getStock()+1);
							}
							if(provideCommodity.getCommodityState()==null||provideCommodity.getCommodityState()==0||provideCommodity.getSalesVolume()<=0){
								provideCommodity.setSalesVolume(0);
							}else{
								provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()-1);
							}
							if(provideCommodity.getType().equals("3")&&provideCommodity.getCommodityState()==7&&provideCommodity.getRegistrationEndTime().after(new Date())){
								provideCommodity.setCommodityState(2);
							}
							orderForm.setCommission(new BigDecimal(0.00));
							orderForm.setBail(new BigDecimal(0.00));
							orderForm.setOrderStatus("11");
							orderForm.setPreferentialMoney(0.00);
							//orderForm.setCouponid("");
							if(preferentialMoney!=0.00){
								orderForm.setReturnPreferentialMoney(preferentialMoney);
							}
							orderForm.setCouponName("");
							orderForm.setRealPrice(0.00);
							
							if(orderForm.getSpikeid()!=null){
								OperatorSecckill secckill=operatorSecckillRepository.findOne(orderForm.getSpikeid());
								secckill.setSkNum(secckill.getSkNum()+1);
								secckill.setSkSellNum(secckill.getSkSellNum()-1);
								operatorSecckillRepository.save(secckill);
							}
							
						}else{
							orderForm.setFullOrPartRefunds("1");
							Double newpreferentialMoney=(preferentialMoney*(orderForm.getRealPrice()-amount-preferentialMoney))/(orderForm.getRealPrice()-preferentialMoney);
							DecimalFormat df = new DecimalFormat("######0.00"); 
							orderForm.setPreferentialMoney(Double.parseDouble(df.format(newpreferentialMoney)));
							orderForm.setRealPrice(orderForm.getRealPrice()-preferentialMoney-amount);
							if(preferentialMoney!=0.00){
								orderForm.setReturnPreferentialMoney(Double.parseDouble(df.format(preferentialMoney-newpreferentialMoney)));
							}
						}
						orderForm.setRefundsAmount(amount);
						
						int price=Integer.parseInt(new DecimalFormat("#").format(amount*100));
						
						String url=ApiController.PAY_URL+"askRefund.php";
						String param="isJava=1&id="+orderForm.getDefrayNumber()+"&ask_name="+orderForm.getUser().getUsername()
								+"&ask_amount="+price+"&ask_description="+URLEncoder.encode("订单关闭发起退款", "UTF-8");
						String json=SystemHelper.httpGetHelper(url, param);
						
						if(json.indexOf("SUCCESS")<=0){
							returnResult.setKey("error");
				    		returnResult.setValue("提交退款失败，请重新处理");
						}else{
							beSave="1";
						}
						
					}
				}
			}else{
				returnResult.setKey("error");
				returnResult.setValue("订单状态不允许此操作");
			}
			if(beSave.equals("1")){
				orderForm.setCloseTime(new Date());
				orderForm.setCloseType("4");
				provideOrderFormRepository.save(orderForm);
				provideCommodityRepository.save(provideCommodity);
				if(puCoupon!=null){
					personalUserCouponRepository.save(puCoupon);
				}
				if(oCoupons!=null){
					operatorCouponsRepository.save(oCoupons);
				}
				returnResult.setKey("success");
	    		returnResult.setValue("订单已关闭");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 服务商完成服务
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 上午11:14:05     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult completeServe(String id){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("3")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				orderForm.setOrderStatus("4");
				orderForm.setApplyforCompleteTime(new Date());
				orderForm.setIsRead("1");
				provideOrderFormRepository.save(orderForm);
				returnResult.setKey("success");
	    		returnResult.setValue("完成服务成功");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 完成退款
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 下午2:03:06     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult confirmRefunds(String id) throws Exception{
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("5")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				orderForm.setFullOrPartRefunds("1");
				int price=0;
				if(orderForm.getRefundsAmount()!=null){
					price=Integer.parseInt(new DecimalFormat("#").format(orderForm.getRefundsAmount()*100));
				}
				String url=ApiController.PAY_URL+"askRefund.php";
				String reason="无";
				if(orderForm.getRefundsReason()!=null&&!orderForm.getRefundsReason().equals("")){
					reason=orderForm.getRefundsReason();
				}
				String param="isJava=1&id="+orderForm.getDefrayNumber()+"&ask_name="+orderForm.getUser().getUsername()
						+"&ask_amount="+price+"&ask_description="+URLEncoder.encode(reason, "UTF-8");;
				String json=SystemHelper.httpGetHelper(url, param);
				if(json.indexOf("SUCCESS")>0){
					Double preferentialMoney=0.00;
					if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
						preferentialMoney=orderForm.getPreferentialMoney();
					}
					if(orderForm.getRealPrice()-orderForm.getRefundsAmount()-preferentialMoney==0){
						orderForm.setFullOrPartRefunds("2");
						if(preferentialMoney>0){
							if(orderForm.getSpikeid()==null||orderForm.getSpikeid().equals("")){
								PersonalUserCoupon puCoupon=personalUserCouponRepository.findOne(orderForm.getCouponid());
								puCoupon.setIsUsed("0");
								personalUserCouponRepository.save(puCoupon);
								OperatorCoupons oCoupons=puCoupon.getOperatorCoupon();
								oCoupons.setBeenused(oCoupons.getBeenused()-1);
								operatorCouponsRepository.save(oCoupons);
							}
							//orderForm.setCouponid("");
							if(preferentialMoney!=0.00){
								orderForm.setReturnPreferentialMoney(preferentialMoney);
							}
							orderForm.setCouponName("");
						}
						ProvideCommodity provideCommodity=orderForm.getCommodity();
						if(provideCommodity.getStock()==null){
							provideCommodity.setStock(1);
						}else{
							provideCommodity.setStock(provideCommodity.getStock()+1);
						}
						if(provideCommodity.getCommodityState()==null||provideCommodity.getCommodityState()==0||provideCommodity.getSalesVolume()<=0){
							provideCommodity.setSalesVolume(0);
						}else{
							provideCommodity.setSalesVolume(provideCommodity.getSalesVolume()-1);
						}
						if(provideCommodity.getType().equals("3")&&provideCommodity.getCommodityState()==7&&provideCommodity.getRegistrationEndTime().after(new Date())){
							provideCommodity.setCommodityState(2);
						}
						provideCommodityRepository.save(provideCommodity);
						
						if(orderForm.getSpikeid()!=null){
							OperatorSecckill secckill=operatorSecckillRepository.findOne(orderForm.getSpikeid());
							secckill.setSkNum(secckill.getSkNum()+1);
							secckill.setSkSellNum(secckill.getSkSellNum()-1);
							operatorSecckillRepository.save(secckill);
						}
					}
					Double newpreferentialMoney=(preferentialMoney*(orderForm.getRealPrice()-orderForm.getRefundsAmount()-preferentialMoney))/(orderForm.getRealPrice()-preferentialMoney);
					DecimalFormat df = new DecimalFormat("######0.00"); 
					orderForm.setPreferentialMoney(Double.parseDouble(df.format(newpreferentialMoney)));
					orderForm.setRealPrice(orderForm.getRealPrice()-preferentialMoney-orderForm.getRefundsAmount()+orderForm.getPreferentialMoney());
					if(preferentialMoney!=0.00){
						orderForm.setReturnPreferentialMoney(Double.parseDouble(df.format(preferentialMoney-newpreferentialMoney)));
					}
					orderForm.setOrderStatus("10");
					orderForm.setConfirmRefundsTime(new Date());
					orderForm.setIsRead("1");
					
					if(orderForm.getPaymentMethod()!=null&&(orderForm.getPaymentMethod().equals("wx_pub_qr")||orderForm.getPaymentMethod().equals("alipay_pc_direct")||orderForm.getPaymentMethod().equals("alipay")||orderForm.getPaymentMethod().equals("wx"))){
						
						int price1=Integer.parseInt(new DecimalFormat("#").format(orderForm.getRealPrice()*100));
						if(orderForm.getPreferentialMoney()!=null&&orderForm.getPreferentialMoney()>0){
							price1=price1-Integer.parseInt(new DecimalFormat("#").format(orderForm.getPreferentialMoney()*100));
						}
						Map map=JsonAnalyze.getJsonValues(orderForm.getCommodity().getProviderBusiness().getId());
						String totalBail=(String)map.get("totalBail");
						String bail_rate=(String)map.get("bail_rate");
						String commission_rate=(String)map.get("commission_rate");
						int sumBail=provideOrderFormDao.getSumBail(orderForm.getCommodity().getProviderBusiness().getId());
						
						//orderForm.setFee(new BigDecimal(orderForm.getRealPrice()*6/1000));
						//price1=price1-Integer.parseInt((orderForm.getFee().doubleValue() * 100 + "").substring(0, (orderForm.getFee().doubleValue() * 100 + "").indexOf(".")));
						if(totalBail!=null&&Integer.parseInt(totalBail)>sumBail){
							int rate=10;
							if(bail_rate!=null&&Integer.parseInt(bail_rate)>1&&Integer.parseInt(bail_rate)<100){
								rate=Integer.parseInt(bail_rate);
							}
							int bail=0;
							if(price1*rate/100<(Integer.parseInt(totalBail)-sumBail)){
								bail=price1*rate/100;
							}else{
								bail=Integer.parseInt(totalBail)-sumBail;
							}
							Double double1=(double) bail;
							orderForm.setBail(new BigDecimal(double1/100));
							
							//price1=price1-bail;
						}
						int c_rate=10;
						if(commission_rate!=null&&Integer.parseInt(commission_rate)>1&&Integer.parseInt(commission_rate)<100){
							c_rate=Integer.parseInt(commission_rate);
						}
						Double double2=(double) price1*c_rate/100;
						orderForm.setCommission(new BigDecimal(double2/100));
						
					}
					
					provideOrderFormRepository.save(orderForm);
					returnResult.setKey("success");
		    		returnResult.setValue("服务商已向财务平台申请退款");
		    		
		    		String telephone=orderForm.getContactNumber();
		    		String message="尊敬的用户您好，您的服务订单"+orderForm.getOrderNumber()+"退款已成功受理，将返回您原支付账户，请在1-15个工作日内注意查收，如有疑问请致电国安创客：4008518585，感谢您对“国安创客”平台的支持与信任。";
		    		SystemHelper.sendMessage(telephone, message);
		    		
				}else{
					returnResult.setKey("error");
		    		returnResult.setValue("发起退款失败，请重新操作");
				}
				
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 拒绝退款
	* @param id 订单id
	* @param denyRefundsReason 拒绝退款原因
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月13日 下午2:08:16     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult denyRefunds(String id,String denyRefundsReason)throws Exception{
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(!orderForm.getOrderStatus().equals("5")){
				returnResult.setKey("error");
				returnResult.setValue("订单当前状态不允许此操作");
			}else{
				orderForm.setOrderStatus("9");
				orderForm.setDenyRefundsTime(new Date());
				orderForm.setDenyRefundsReason(denyRefundsReason);
				orderForm.setIsRead("1");
				String remark="用户于"+orderForm.getApplyforRefundsTime()+"申请退款"+orderForm.getRefundsAmount()+"元，商家于"+orderForm.getDenyRefundsTime()+"拒绝了该笔退款申请。";
				orderForm.setCloseRefundsRemark(remark);
				provideOrderFormRepository.save(orderForm);
				
				OperatorQuestionOrder opOrder=new OperatorQuestionOrder();
				opOrder.setComplaintNum(SystemHelper.getWorkOrderNumber());
				opOrder.setLoginid("系统");
				opOrder.setCreateTime(new Date());
				opOrder.setComplainId("订单投诉");
				opOrder.setOrderleveid("2");
				opOrder.setName(orderForm.getUser().getNickname());
				opOrder.setPhone(orderForm.getContactNumber());
				opOrder.setAndrelationid("0");
				opOrder.setQuestionContent("商户拒绝退款");
				opOrder.setAccusedName(orderForm.getCommodity().getProviderBusiness().getBusinessName());
				opOrder.setAccusedPhone(orderForm.getCommodity().getProviderBusiness().getLicensPhone());
				opOrder.setAccuseandrelationid("1");
				opOrder.setOrderStatus("5");
				opOrder.setOrderNum(orderForm.getOrderNumber());
				operatorQuestionOrderRepository.save(opOrder);
				
				returnResult.setKey("success");
	    		returnResult.setValue("拒绝退款成功");
	    		
	    		String telephone=orderForm.getContactNumber();
	    		String message="尊敬的用户您好，您的服务订单"+orderForm.getOrderNumber()+"退款服务商已拒绝退款，届时国安创客工作人员会与您沟通确认，为保证订单退款顺利，请您保证电话实时通畅，如有疑问请致电国安创客：4008518585，感谢您对“国安创客”平台的支持与信任。";
	    		SystemHelper.sendMessage(telephone, message);
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 修改订单为已读
	* @param id 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月21日 上午10:37:55     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult isRead(String id){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(id);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			orderForm.setIsRead("1");
			provideOrderFormRepository.save(orderForm);
			returnResult.setKey("success");
    		returnResult.setValue("修改订单为已读成功");
		}
		
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 将服务商要求的特定类型订单设置为已读
	* @param businessid 服务商id
	* @param state 订单类型
	* @author Yvonne_MGL 
	* @date 2017年9月13日 下午7:17:13     
	* @return void    
	* @throws 
	 */
	@Transactional
	public void isReadAll(String businessid,String state){
		List<ProvideOrderForm> list=provideOrderFormDao.findUnReadOrders(businessid, state);
		if(list!=null){
			for (int i = 0; i < list.size(); i++) {
				ProvideOrderForm orderForm=list.get(i);
				orderForm.setIsRead("1");
				provideOrderFormRepository.save(orderForm);
			}
		}
	}
	/**
	 * 
	* @Description: 查询未读订单数量
	* @param businessid 服务商id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月21日 上午11:01:20     
	* @return UnreadOrderNum    
	* @throws 
	 */
	public UnreadOrderNum findUnread(String businessid){
		return provideOrderFormDao.findUnread(businessid);
	}
	
	/**
	 * 
	* @Description: 查询订单发票情况 
	* @param invoiceState 开发票状态
	* @param priceBegin 起始价格
	* @param priceEnd 结束价格
	* @param orderNumber 订单编号
	* @param commodityName 商品名称
	* @param pageNumber  分页页数 ,从0开始
	* @param pageSize  分页每业条数
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月27日 下午4:58:40     
	* @return Map    
	* @throws 
	 */
	public Map findInvoiceOrderForm(String invoiceState, Double priceBegin, Double priceEnd,String orderNumber,String commodityName, Integer pageNumber, Integer pageSize,String businessid){
		return provideOrderFormDao.findInvoiceOrderForm(invoiceState, priceBegin, priceEnd, orderNumber, commodityName, pageNumber, pageSize,businessid);
	}
	
	/**
	 * 
	* @Description: 查询发票 
	* @param invoiceid 发票id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月27日 下午5:18:35     
	* @return PersonalInvoice    
	* @throws 
	 */
	public PersonalInvoice findPersonalInvoice(String invoiceid){
		return personalInvoiceRepository.findOne(invoiceid);
	}
	
	/**
	 * 
	* @Description: 服务商为用户开发票 
	* @param orderid 订单id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年7月27日 下午5:27:21     
	* @return ReturnResult    
	* @throws 
	 */
	@Transactional
	public ReturnResult givePersonalInvoice(String orderid){
		ReturnResult returnResult=new ReturnResult();
		ProvideOrderForm orderForm=provideOrderFormRepository.findOne(orderid);
		if(orderForm==null){
			returnResult.setKey("error");
			returnResult.setValue("订单不存在");
		}else{
			if(orderForm.getInvoiceState()!=null&&orderForm.getInvoiceState().equals("0")){
				orderForm.setInvoiceState("1");
				provideOrderFormRepository.save(orderForm);
				returnResult.setKey("success");
	    		returnResult.setValue("操作成功");
			}else{
				returnResult.setKey("error");
				returnResult.setValue("订单状态不允许此操作");
			}
		}
		return returnResult;
	}
	
	/**
	 * 
	* @Description: 查询服务商评价详情 
	* @param businessid 服务商id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年8月29日 下午9:54:46     
	* @return Map    
	* @throws 
	 */
	public Map getBusinessAppraise(String businessid, Integer pageNumber, Integer pageSize){
		return personalAppraiseDao.getBusinessAppraise(businessid,pageNumber,pageSize);
	}
	
	/**
	 * 
	* @Description: 根据服务商id查询服务商的佣金、手续费、保证金总额 
	* @param businessid 服务商id
	* @param @return
	* @author Yvonne_MGL 
	* @date 2017年11月14日 上午10:19:59     
	* @return Map    
	* @throws 
	 */
	public Map getStatistics(String businessid){
		return provideOrderFormDao.getStatistics(businessid);
	}
	
	/**
	 * 
	* @Description: 初始化returnPreferentialMoney 
	* @param 
	* @author Yvonne_MGL 
	* @date 2017年11月15日 上午10:06:00     
	* @return void    
	* @throws 
	 */
	@Transactional
	public void initializeReturnPreferentialMoney(){
		List<ProvideOrderForm> list=provideOrderFormDao.getRefundsOrder();
		if(list!=null&&list.size()>0){
			for (int i = 0; i <list.size(); i++) {
				ProvideOrderForm orderForm=list.get(i);
				orderForm.setReturnPreferentialMoney(orderForm.getTruePrice()-orderForm.getRefundsAmount()-orderForm.getRealPrice());
				provideOrderFormRepository.save(orderForm);
			}
		}
	}
	
}
